package com.crm.CLdriving.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.crm.CLdriving.dto.req.RegisterReqDto;
import com.crm.CLdriving.dto.resp.RegisterRespDto;
import com.crm.CLdriving.exception.MyServiceException;
import com.crm.CLdriving.mapper.UserMapper;
import com.crm.CLdriving.po.UserPO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.crm.CLdriving.common.BaseResponse;
import com.crm.CLdriving.dto.req.LoginReqDto;
import com.crm.CLdriving.dto.resp.LoginRespDto;
import com.crm.CLdriving.enu.ResponseEnum;
import com.crm.CLdriving.mapper.LoginMapper;
import com.crm.CLdriving.po.LoginPO;
import com.crm.CLdriving.service.LoginService;
import com.crm.CLdriving.util.token.TokenUtils;

import lombok.extern.log4j.Log4j2;

import java.util.HashMap;

@Transactional
@Service
@Log4j2
public class LoginServiceImpl implements LoginService {

	@Autowired
	private LoginMapper loginMapper;

	@Autowired
	private UserMapper userMapper;

	/**
	 * 登录
	 * @param loginReqDto
	 * @return
	 */
	@Override
	public BaseResponse<LoginRespDto> login(LoginReqDto loginReqDto) {
		
		LoginPO loginPO = new LoginPO();
		loginPO.setLoginUserName(loginReqDto.getUsername());
		loginPO.setLoginPassWord(loginReqDto.getPassword());
		LoginPO login = loginMapper.selectOne(loginPO);			
		LoginRespDto response = new LoginRespDto();
		if (login != null) {
			log.info("登录查询返回数据"+ login);
			String token = TokenUtils.genToken(loginReqDto.getUsername(),loginReqDto.getPassword());
			response.setLoginUserName(login.getLoginUserName());
			response.setLoginPassWord(login.getLoginPassWord());
			response.setToken(token);		
			return BaseResponse.successOf(response);
		}				
		return BaseResponse.message(ResponseEnum.LOGINFAIL);
	}

	/**
	 * 使用账号密码注册
	 * 记录密码、用户名
	 * @param registerReqDto
	 * @return
	 */
	@Override
	public BaseResponse<RegisterRespDto> register(RegisterReqDto registerReqDto){

			String psw = registerReqDto.getPassword();
			UserPO user = new UserPO();
			user.setName(registerReqDto.getUsername());
			user.setPassword(SecureUtil.md5(psw));
			user.setRoles(registerReqDto.getRoles());
			userMapper.insert(user);

			RegisterRespDto registerRespDto = new RegisterRespDto();
			registerRespDto.setAvatar("");
			registerRespDto.setRoles(registerReqDto.getRoles());
			registerRespDto.setUsername(registerReqDto.getUsername());
			registerRespDto.setToken(TokenUtils.genToken(user.getName(), user.getPassword()));

			return BaseResponse.successOf(registerRespDto);

	}


}
